import 'dart:async';
import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';

import 'company_search_detail_list_item_widget.dart';


/// 企业详情-根据类型显示列表

class CompanySearchDetailListWidget extends StatefulWidget {
  final GroupPersonCntBean groupInfoBean;

  final ValueNotifier<String> searchPageValueNotifier;


  const CompanySearchDetailListWidget(
      {Key key, this.groupInfoBean, this.searchPageValueNotifier})
      : super(key: key);

  @override
  CompanySearchDetailListWidgetState createState() =>
      CompanySearchDetailListWidgetState();
}

class CompanySearchDetailListWidgetState extends BasePagerState<
    CompanyDetailByTypeListItemBean, CompanySearchDetailListWidget>with AutomaticKeepAliveClientMixin, VgPlaceHolderStatusMixin{
  // List<String> userIds;
  ValueNotifier<String> searchPageValueNotifier;
  CommonListPageWidgetState mState;
  StreamSubscription streamSubscription;
  List<CompanyDetailByTypeListItemBean> itemBeanListSearch;
  String searchDetailKey = SP_SEARCH_DETAIL+UserRepository.getInstance().getCompanyId();
  @override
  void initState() {
    super.initState();
    itemBeanListSearch = List<CompanyDetailByTypeListItemBean>();
    searchPageValueNotifier = widget?.searchPageValueNotifier;
    // userIds = List<String>();
    _getShareStringList();
    streamSubscription = VgEventBus.global.on<SearchRefreshEvent>().listen((event) {
      _getShareStringList();
    });
    searchPageValueNotifier?.addListener(_refreshSearch);
    setState(() { });
  }

  // void _getShareStringList(){
    // SharePreferenceUtil.getStringList(UserRepository.getInstance().getCompanyId()).then((value){
    //   if(value?.length == 0){
    //     userIds = [];
    //     mState?.viewModel?.refresh();
    //     return;
    //   }
    //   value?.forEach((element) {
    //     userIds = value;
    //   });
    //   mState?.viewModel?.refresh();
    // });
  // }

  ///直接读取缓存
  @override
  void _getShareStringList() {
    // _getCacheUserInfo().then((userJsonStr){
    //   if (userJsonStr == null || userJsonStr == "" || userJsonStr == "[]") {
    //     return;
    //   }
      SharePreferenceUtil.getString(searchDetailKey).then((userJsonStr){
        if (userJsonStr == null || userJsonStr == "" || userJsonStr == "[]") {
          itemBeanListSearch = null;
          mState?.viewModel?.refresh();
          return;
        }
          var listDynamic = jsonDecode(userJsonStr);
          List<CompanyDetailByTypeListItemBean> M = List<CompanyDetailByTypeListItemBean>();
        List<CompanyDetailByTypeListItemBean> Mmaps = List<CompanyDetailByTypeListItemBean>();
          List<Map<String ,dynamic>>  map = List<Map<String ,dynamic>>.from(listDynamic);
          // List<CompanyDetailByTypeListItemBean> M = new List();
          // map.forEach((element) => M.add(CompanyDetailByTypeListItemBean.fromMap(element)));
          // List<String> fuids = List<String>();
          // M?.forEach((element) {
          //   fuids?.add(element?.fuid);
          // });
            map.forEach((element) => M.add(CompanyDetailByTypeListItemBean.fromMap(element)));
        M?.forEach((element) {
          Mmaps?.insert(0, element);
        });
          itemBeanListSearch = Mmaps;

        mState?.viewModel?.refresh();
      });
      setState(() { });
    // });
    // CompanyDetailByTypeListItemBean userDataBean = CompanyDetailByTypeListItemBean.fromMap(jsonDecode(userJsonStr));
    // CompanyDetailByTypeListResponseBean userDataBean = CompanyDetailByTypeListResponseBean?.fromMap(jsonDecode(userJsonStr));
  }

  ///获取用户缓存
  // Future<String> _getCacheUserInfo() {
  //   return SharePreferenceUtil.getString(KEY_SEARCH_DETAIL);
  // }


  void _refreshSearch(){
    // if(searchPageValueNotifier?.value==null||searchPageValueNotifier?.value==""){
    //   searchPageValueNotifier?.value = "%-%";
    // }
    mState?.viewModel?.refresh();
    setState(() { });
  }

  @override
  void dispose() {
    streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 3),
        // _listSearchView()
        _toListWidget()
        // (itemBeanListSearch?.length ?? 0)==0&&searchPageValueNotifier?.value==null||searchPageValueNotifier?.value=="" ? _defaultEmptyCustomWidget():_toListWidget()
      ],
    );
  }

  Widget _defaultEmptyCustomWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 180),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Image.asset("images/empty_icon.png",width: 120,gaplessPlayback: true,),
          Text(
            "暂无搜索记录",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 13,
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
  //
  // Widget _listSearchView(){
  //   return Expanded(
  //     child: ListView.separated(
  //       padding: EdgeInsets.only(top: 0),
  //       shrinkWrap: true,
  //       itemBuilder: (BuildContext context, int index) {
  //
  //         return CompanySearchDetailListItemWidget(itemBean: itemBeanListSearch[index],);
  //       },
  //       separatorBuilder: (BuildContext context, int index){
  //         return Container(
  //           height: 0.5,
  //           color: ThemeRepository.getInstance().getCardBgColor_21263C(),
  //           padding: const EdgeInsets.only(left: 15),
  //           child: Container(
  //             color: Color(0xFF303546),
  //           ),
  //         );
  //       },
  //       itemCount: itemBeanListSearch?.length??0,
  //     )
  //   );
  // }

  Widget _toListWidget() {
    return Expanded(
      child: CommonListPageWidget<CompanyDetailByTypeListItemBean, CompanyDetailByTypeListResponseBean>(
        enablePullUp: true,
        enablePullDown: true,
        isInitRefresh:false,
        queryMapFunc: (int page) => {
          "authId": UserRepository.getInstance().authId ?? "",
          "current": page ?? 1,
          "size": 50,
          "groupid": widget?.groupInfoBean?.groupid ?? "",
          "groupType": widget?.groupInfoBean?.groupType ?? "",
          "searchName": widget?.searchPageValueNotifier?.value == null || widget?.searchPageValueNotifier?.value == "" ?"%-&-@-%" :widget?.searchPageValueNotifier?.value,
          // "searchOthers": searchPageValueNotifier?? "",
        },
        parseDataFunc: (VgHttpResponse resp) {
          CompanyDetailByTypeListResponseBean vo =
          CompanyDetailByTypeListResponseBean.fromMap(resp?.data);
          loading(false);
          if((itemBeanListSearch?.length ?? 0)!=0&&widget?.searchPageValueNotifier?.value == null || widget?.searchPageValueNotifier?.value == ""){
            // List<CompanyDetailByTypeListItemBean> records = List<CompanyDetailByTypeListItemBean>();
            // vo?.data?.page?.records?.forEach((element) {
            //   if(userIds?.toString()?.contains(element?.fuid)){
            //     records?.add(element);
            //   }
            // });
            vo?.data?.page?.records = itemBeanListSearch;
          }
          return vo;
        },
        // listFunc: (List<CompanyDetailByTypeListItemBean> companySearchItemList) {
        // },
        stateFunc: (CommonListPageWidgetState state) {
          mState = state;
        },
        itemBuilder: (BuildContext context, int index,
            CompanyDetailByTypeListItemBean itemBean) {

          // if (itemBean == null) return _defaultEmptyCustomWidget();
          return CompanySearchDetailListItemWidget(itemBean: itemBean,searchPageValueNotifier: widget?.searchPageValueNotifier,);
        },
        //分割器构造器
        separatorBuilder: (context, int index, _) {
          return Container(
            height: 0.5,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: const EdgeInsets.only(left: 15),
            child: Container(
              color: Color(0xFF303546),
            ),
          );
          // return divider;
        },
        placeHolderFunc: (List<CompanyDetailByTypeListItemBean> list, Widget child,
            VoidCallback onRefresh) {
          return VgPlaceHolderStatusWidget(
            emptyStatus: list == null || list.isEmpty,
            emptyOnClick: () => onRefresh(),
            emptyCustomWidget: _defaultEmptyCustomWidget(),
            child: child,
          );
        },
        netUrl:ServerApi.BASE_URL + "app/appCompanyPages",
        httpType: VgHttpType.get,
      ),
    );
  }
}

